<?php

class LoginServiceController extends CController
{
	public function actions()
	{
		return array(
				'japi'=>'JApi',
		);
	}

	public function japiTest($required,$optional="abc")
	{
		return array('r'=>$required,'o'=>$optional);
	}

	public function japiLogin($mse)
	{
		$mseLoginDTO = Transformer::jsonToModel(CJSON::decode($mse));

		$mss = new MSSConfirmacionDTO();
		if($mseLoginDTO instanceof MSELoginDTO){
			$loginForm= $mseLoginDTO->loginDTO;
			$logged = $loginForm->login();

			if($logged){
				$mss->result=1;
				$mss->message=Yii::app()->getSession()->getSessionID();
				return $mss->toJson();
			}else{
				$mss->result=-1;
				$mss->message="Login or Password error";
				return $mss->toJson();
			}
		}
		$mss->result=-2;
		$mss->message="Fatal Error";
		return $mss->toJson();
	}



	public function japiRegister($mse)
	{
		$mseUserDTO = Transformer::jsonToModel(CJSON::decode($mse));

		$mss = new MSSConfirmacionDTO();
		if($mseUserDTO instanceof User){
			try{
				
				if($mseUserDTO->save()){
					$mss->result=1;
					$mss->message="Confirmación";
					return $mss->toJson();
				}else{
					$mss->result=-1;
					$mss->message="Error al crear usuario.";
					return $mss->toJson();
				}

			}catch (CDbException $exception){
				$mss->result=-3;
				$mss->message="Ya existe un usuario con ese nombre ". $mseUserDTO->username ;
				return $mss->toJson();
			}
		}else{
			$mss->result=-2;
			$mss->message="Error en los parametros de entrada.";
			return $mss->toJson();
		}


	}

	public function japiLogout()
	{
		$mss = new MSSConfirmacionDTO();
		Yii::app()->user->logout();
		$mss->result=1;
		$mss->message="Exito";
		return $mss->toJson();
	}

}
